using System;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Collections;
using System.Drawing;
using System.Workflow.ComponentModel;
using System.Workflow.ComponentModel.Design;
using System.Workflow.ComponentModel.Compiler;
using System.Workflow.ComponentModel.Serialization;
using System.Workflow.Runtime;
using System.Workflow.Activities;
using System.Workflow.Activities.Rules;


using System.Data.Linq;
using System.Linq;

using DataLayer;

namespace BusinessLayer.Activities
{
   public partial class Create_Tab : System.Workflow.ComponentModel.Activity
   {
      public Create_Tab()
      {
			//InitializeComponent();
      }

      private static DependencyProperty TabIdProperty = DependencyProperty.Register("TabId", typeof(int), typeof(Create_Tab));
      public int TabId
      {
         get { return (int)base.GetValue(TabIdProperty); }
         set { base.SetValue(TabIdProperty, value); }
      }

      private static DependencyProperty UserGuidProperty = DependencyProperty.Register("UserGuid", typeof(Guid), typeof(Create_Tab));
      public Guid UserGuid
      {
         get { return (Guid)base.GetValue(UserGuidProperty); }
         set { base.SetValue(UserGuidProperty, value); }
      }

      protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext)
      {
         using (var db = DatabaseHelper.GetDashboardData())
         {
            //add a new tab
            var newTab = new Tab();
            newTab.UserId = UserGuid;
            newTab.Title = "New Page";
            newTab.CreatedDate = DateTime.Now;
            newTab.LastUpdate = DateTime.Now;
            newTab.PanelWidth_1 = 33;
            newTab.PanelWidth_2 = 34;
            newTab.PanelWidth_3 = 33;
            newTab.PanelWidth_4 = 0;
            newTab.Icon = "";
            DatabaseHelper.Insert<Tab>(newTab);

            //link user to this tab
            var newUserTab = new UserTab();
            newUserTab.AccessLevel = 0;
            newUserTab.TabId = newTab.ID;
            newUserTab.UserID = UserGuid;
            //default guid is the individual role, no user belongs to this role
            newUserTab.RoleID = Constants.Role_Individual;
            newUserTab.Deleted = false;

            //add page to end of the pages list
            var P = from p in db.UserTabs
                    where p.UserID == UserGuid
                    orderby p.Order descending
                    select p.Order;
            
            if (P.Count() > 0)
            {
               newUserTab.Order = Convert.ToByte(P.First() + 1);
            }
            else
            {
               newUserTab.Order = 0;
            }

            DatabaseHelper.Insert<UserTab>(newUserTab);

            TabId = newTab.ID;
         }
         return ActivityExecutionStatus.Closed;
      }
   }
}